﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using WoodAdmin.Common.Filter;
using WoodAdmin.Common.Helper;
using WoodAdmin.Common.Helper.Log;
using WoodAdmin.Models;
using SqlSugar;

namespace WoodAdmin.Controllers
{
    [CheckLoginFilter, CheckPermissionFilters, ExceptionGlobalFilter]
    public class BaseController : Controller
    {
        /// <summary>
        /// 数据库连接对象
        /// </summary>
        protected SqlSugarClient Db { get; } = DbContext.Db;

        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        public virtual SysUser CurrentUser { get => GlobalHelper.CurrentUser(); }

        /// <summary>
        /// 返回json成功提示
        /// </summary>
        /// <param name="message"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public IActionResult JsonSuccess(string message="操作成功", object obj = null)
        {
            return Json(new { status = 1, msg = message, data = obj });
        }

        /// <summary>
        /// 返回json错误提示
        /// </summary>
        /// <param name="message"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ActionResult JsonError(string message="操作失败", object obj = null)
        {
            return Json(new { status = 0, msg = message, data = obj });
        }

        #region 日志处理
        /// <summary>
        /// 操作日志处理
        /// </summary>
        private OperationLogHandler _operationLogHandler;

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _operationLogHandler = new OperationLogHandler(context.HttpContext.Request);
            _operationLogHandler.LogInfo.CreateAccountId = CurrentUser?.ID.ToString() ?? string.Empty;
            _operationLogHandler.LogInfo.CreateUserName = CurrentUser == null ? "匿名用户" : CurrentUser.NickName;
            _operationLogHandler.LogInfo.ControllerName = context.ActionDescriptor.RouteValues["controller"];
            _operationLogHandler.LogInfo.ActionName = context.ActionDescriptor.RouteValues["action"];
            var des = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttributes(false).Where(f => f is DescriptionAttribute).FirstOrDefault();
            if (des != null)
            {
                _operationLogHandler.LogInfo.Description = (des as DescriptionAttribute).Description;
            }
            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            _operationLogHandler.ActionExecuted();
            _operationLogHandler.ResultExecuted(context.HttpContext.Response);
            _operationLogHandler.WriteLog();
            base.OnActionExecuted(context);
        }
        #endregion
    }
}